package org.thesis.secutity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;
import android.util.Log;

public class TripleDEScontrol 
{
	final static String TRIPLEDES = "DESede";
	final static String LOAIBYTE = "utf8";
	Cipher Cip;
	SecretKeySpec mykey;
	FileInputStream fis;
	FileOutputStream fos;
	String tag = "TripleDEScontrol";
	public TripleDEScontrol(SecretKeySpec mykey) {
		super();
		this.mykey = mykey;
	}
	
	public String encrypt(String input)
	{
		String output = "";
		try {
			Cip = Cipher.getInstance(TRIPLEDES);
			Cip.init(Cipher.ENCRYPT_MODE, mykey);
			byte[]utf8 = input.getBytes(LOAIBYTE);
			byte []enc = Cip.doFinal(utf8);
			output = Base64.encodeToString(enc, 0);
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Loi ma hoa " + e.toString());
		}
		return output;
	}
	
	public String decrypt(String input)
	{
		String output = "";
		try {
			Cip = Cipher.getInstance(TRIPLEDES);
			Cip.init(Cipher.DECRYPT_MODE, mykey);
			byte []dec = Base64.decode(input, 0);
			byte []utf8 = Cip.doFinal(dec);
			output = new String(utf8, LOAIBYTE);
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Loi giai ma " + e.toString());
		}
		return output;
	}
	 public void EncFile (String input, String output)
	    {
	        try
	        {
	            Cip = Cipher.getInstance(TRIPLEDES);
	            Cip.init(Cipher.ENCRYPT_MODE, mykey);
	            File fi = new File(input);
	            File fo = new File(output);
	            fis = new FileInputStream(fi);
	            CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(fo), Cip);
	            copy(fis, cos);
	            cos.close();
	            fis.close();

	        }
	        catch(Exception e)
	        {
	        	 Log.v(tag, "Loi ma hoa file DES" + e.toString());
	        }
	    }
	    public void DecFile(String input, String output)
	    {
	        try
	        {
	            Cip = Cipher.getInstance(TRIPLEDES);
	            Cip.init(Cipher.DECRYPT_MODE, mykey);
	            CipherInputStream cis = new CipherInputStream(new FileInputStream(input), Cip);
	            fos = new FileOutputStream(output);
	            copy(cis, fos);
	            cis.close();
	            fos.close();
	        }
	        catch(Exception e)
	        {
	            Log.v(tag, "Loi giai ma file DES" + e.toString());
	        }
	    }
	     private void copy(InputStream is, OutputStream os) throws IOException {
			int i;
			byte[] b = new byte[1024];
			while((i=is.read(b))!=-1) {
				os.write(b, 0, i);
			}
		}
	
}
